<?php
namespace Tbf\Bundle\TestBundle\Logger;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

/**
 * 测试用跨请求保存log记录,并且log记录可以被php自己读取出来
 */
class RecordLoggerHandler extends AbstractProcessingHandler
{
    protected $file_name = null;
    public function __construct($file_name)
    {
        $this->file_name = $file_name;
        parent::__construct(Logger::DEBUG,true);
    }

    /**
     * 先读出原来的旧数据,再加上这次的记录,再重新写入
     * 并发不安全!!
     * @param  array $record
     * @return void
     */
    protected function write(array $record)
    {
        $old = $this->readLog();
        $old[] = $record['formatted'];
        $toWrite = json_encode($old,JSON_PRETTY_PRINT);
        file_put_contents($this->file_name,$toWrite);
    }

    /**
     * 读出所有log
     * 并发不安全!!
     * @return array
     */
    public function readLog()
    {
        try{
            $content = @file_get_contents($this->file_name);
        }catch(\Exception $e){
            return array();
        }
        if (empty($content)) {
            return array();
        }
        $data = json_decode($content,true);
        if (empty($data)) {
            return array();
        }

        return $data;
    }

    /**
     * 删除所有已有log
     * 并发不安全!!
     */
    public function cleanLog()
    {
        file_put_contents($this->file_name,'[]');
    }

    protected function getDefaultFormatter()
    {
        return new NormalizerFormatter();
    }

}
